# 构建阶段 - 安装依赖
FROM python:3.11-slim as builder

WORKDIR /build

# 安装编译工具
RUN apt-get update && \
    apt-get install -y gcc curl && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

# 安装Python依赖
COPY requirements.txt .
RUN pip install --user --no-cache-dir -r requirements.txt gunicorn

# 应用阶段 - 运行应用
FROM python:3.11-slim

# 设置环境
ENV TZ=Asia/Shanghai \
    PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    APP_MODE=production

# 安装curl并创建非root用户
RUN apt-get update && \
    apt-get install -y curl && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/* && \
    groupadd -g 1000 appuser && \
    useradd -u 1000 -g appuser -m appuser

WORKDIR /app

# 复制Python包和应用代码
COPY --from=builder /root/.local /home/appuser/.local
ENV PATH=/home/appuser/.local/bin:$PATH
COPY --chown=appuser:appuser . /app

# 创建目录并设置权限
RUN mkdir -p /app/logs /app/uploads && \
    chown -R appuser:appuser /app

USER appuser
EXPOSE 8000

# 健康检查
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
    CMD curl -f http://localhost:8000/api/health || exit 1

# 启动应用
CMD ["gunicorn", "main:app", "-c", "gunicorn.conf", "--bind", "0.0.0.0:8000"]

# 开发模式（取消注释使用）
# CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]